﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Windows.Controls.Primitives;
using System.Windows.Media;

namespace WP8_Client.View
{
    public partial class SplashScreenControl : UserControl
    {
        ClientCore cClientCore;

        public SplashScreenControl(ClientCore pClientCore)
        {            
            this.cClientCore = pClientCore;
            this.cClientCore.OnConnectionEstablished += cClientCore_OnConnectionEstablished;
            this.cClientCore.OnLogedIn_Confirmation += cClientCore_OnLogedIn;
            this.cClientCore.OnLogedIn_Decline += cClientCore_OnLogedInFailed;            
            
            InitializeComponent();
            this.DataContext = App.DefaultViewModel;
        }

        void cClientCore_OnLogedInFailed()
        {
            Deployment.Current.Dispatcher.BeginInvoke(() => MessageBox.Show("LogedInFailed"));
        }

        void cClientCore_OnLogedIn()
        {
            Deployment.Current.Dispatcher.BeginInvoke(() => ((Popup)this.Parent).IsOpen = false);            
        }

        void cClientCore_OnConnectionEstablished()
        {
            Dispatcher.BeginInvoke((Action) delegate
            {
                this.GStatus.Fill = new SolidColorBrush(Colors.Green);
            });            
        }

        private void BtnLogIn_Click(object sender, RoutedEventArgs e)
        {
            App.DefaultViewModel.LogIn();
        }

        void ShowButtons()
        {
            if (this.TbUserName.Text != "" && this.TbPassword.Password != "" && this.cClientCore.IsConnected)
            {
                this.BtnLogIn.IsEnabled = true;
                this.BtnRegister.IsEnabled = true;
            }
        }

        private void TbUserName_TextChanged(object sender, TextChangedEventArgs e)
        {
            this.ShowButtons();
        }

        private void TbPassword_PasswordChanged(object sender, RoutedEventArgs e)
        {
            this.ShowButtons();
        }

        private void BtnRegister_Click(object sender, RoutedEventArgs e)
        {
            App.DefaultViewModel.RegisterNewUser();
        }
    }
}
